import { RuleOptionalStack, RuleOptionalStackSelect, RuleParse } from "../type";

const branchRuleParse: RuleParse = {

	parseType: "branch",

	isNested: true,

	preHandle: (parse, rule, char) => { },

	// branch is branchs's children not need handle
	judge: (parse, rule, char) => {
		const ruleO = rule as unknown as RuleOptionalStack;
		if (char !== "|") {
			return false;
		}
		const parseType = parse.top && parse.top.parseType;
		const ruleSt = ruleO.select;
		if (parseType === "switch") {
			throw new Error("字符组不支持分支");
		}
		if (parseType === "branch") {
			ruleO.back();
			ruleO.push({ ruleType: "branch" as "branchs" });
		} else {
			let afterChildren: RuleOptionalStackSelect[] = [];
			if (ruleSt === undefined) {
				afterChildren = ruleO.origin;
				ruleO.origin = [];
			} else {
				afterChildren = ruleSt.children;
				ruleSt.children = [];
			}
			ruleO.push({ ruleType: "branchs" });
			ruleO.push({ ruleType: "branch" as "branchs" });
			ruleO.selectCheck.children = afterChildren;
			ruleO.back();
			ruleO.push({ ruleType: "branch" as "branchs" });
			parse.push(branchRuleParse);
		}
		return true;
	},

	// [canNested=true]
	handle: (parse, rule, char) => { return false; },
};

export default branchRuleParse;
